package com.situ.skymallproductreviewapi.dao;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.situ.model.ProductReview;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.Map;

@Mapper
public interface ProductReviewMapper extends BaseMapper<ProductReview> {
    default Page<ProductReview> findAll(Page<ProductReview> page,ProductReview productReview){
        LambdaQueryWrapper<ProductReview> qw= Wrappers.lambdaQuery();

        //按商品ID筛选
        if (productReview.getProductId() != null){
            qw.eq(ProductReview::getProductId,productReview.getProductId());
        }
        //按用户ID筛选
        if (productReview.getUserId() != null){
            qw.eq(ProductReview::getUserId,productReview.getUserId());
        }
        //按评分筛选
        if (productReview.getLevel() != null){
            qw.eq(ProductReview::getLevel,productReview.getLevel());
        }
        //按状态筛选
        if (productReview.getStatus() != null){
            qw.eq(ProductReview::getStatus,productReview.getStatus());
        }
        qw.orderByDesc(ProductReview::getTime);
        return selectPage(page,qw);
    }

    @Select("SELECT " +
            "COUNT(*) AS total_count, " +
            "AVG(level) AS avg_level, " +
            "SUM(CASE WHEN level = 0 THEN 1 ELSE 0 END) AS level_0, " +
            "SUM(CASE WHEN level = 1 THEN 1 ELSE 0 END) AS level_1, " +
            "SUM(CASE WHEN level = 2 THEN 1 ELSE 0 END) AS level_2, " +
            "SUM(CASE WHEN level = 3 THEN 1 ELSE 0 END) AS level_3, " +
            "SUM(CASE WHEN level = 4 THEN 1 ELSE 0 END) AS level_4, " +
            "SUM(CASE WHEN level = 5 THEN 1 ELSE 0 END) AS level_5 " +
            "FROM product_review WHERE product_id = #{productId} AND status = 1")
    Map<String, Object> stateByProductId(@Param("productId") Integer productId);
}
